package phone.qyg.com.qyg.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.liaoinstan.springview.container.AliFooter;
import com.liaoinstan.springview.container.AliHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Delete;
import phone.qyg.com.qyg.model.MyCourse;
import phone.qyg.com.qyg.utils.AppHttpRequest;
import phone.qyg.com.qyg.utils.PopuDelete;
import phone.qyg.com.qyg.utils.ProjectDownHintUtil;

/**
 * 作者：lblbh on 2017/12/13 19:04
 * 邮箱：lanbuhan@163.com
 * 功能：我的活动列表
 */
@ContentView(R.layout.my_course_list)
public class MyCourseListActivity extends BaseActivity {

    String STUDENT_COUNT = "已学<font color='#ff6633'>{0}</font>/{1}课";

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.linear)
    LinearLayout linear;

    BaseViewStateLayout baseView;

    CommonAdapter adapter;

    List<MyCourse> models;

    SpringView springview;

    RecyclerView recycler;

    boolean isForce;

    int page_no,totalpage;

    String appInfo;


    @Override
    public void initData(Bundle savedInstanceState) {

        appInfo();

        baseView = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_spring_recycler,null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
                springview = (SpringView) sucessView.findViewById(R.id.springview);

                springview.setListener(new SpringView.OnFreshListener() {
                    @Override
                    public void onRefresh() {
                        isForce = true;
                        getInitNetwork(false);
                    }

                    @Override
                    public void onLoadmore() {
                        if(isRequestList(models) && (page_no < totalpage) ){
                            getInitNetwork(true);
                        }else{
                            PromptManager.showToast(R.string.more_no_datas);
                            springview.onFinishFreshAndLoad();
                        }

                    }
                });

                springview.setHeader(new AliHeader(QXApplication.getContext(),false));
                springview.setFooter(new AliFooter(QXApplication.getContext(),false));
                return sucessView;
            }

            @Override
            public Object obtionData() {
                getInitNetwork(false);
                return DELFAUTSTATE;
            }
        };

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseView,layoutParams);
        x.view().inject(linear);
    }


    /**
     * 执行网络请求
     */
    private void getInitNetwork(final boolean isPull){

        if(isPull){
            page_no = page_no + 1;
        }else{
            page_no = 1;
        }

        if(isForce){
            page_no = 1;
        }

        mapKeys.put(AppHttpKey.PAGE_NO,String.valueOf(page_no));

        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.MY_COURSE_LIST,
                mapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);

                        List<MyCourse> temps = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.COURSE_LIST, MyCourse.class);

                        totalpage = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTALPAGE);

                        if(!isRequestList(temps) && !isPull){
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
                            baseView.stateView();
                            return;
                        }
                        //成功获取到数据
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
                        baseView.stateView();

                        setModelData(isPull,temps);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_ERROE);
                        baseView.stateView();
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        springview.onFinishFreshAndLoad();
                    }
                });
    }

    private void setModelData(final boolean isPull, List<MyCourse> temps) {
        if ((adapter == null && isRequestList(temps)) || isForce) {
            isForce = false;

            //数据初始化工作
            models = temps;

            adapter = new CommonAdapter<MyCourse>(QXApplication.getContext(),R.layout.my_item_course,models) {
                @Override
                protected void convert(ViewHolder holder, final MyCourse model, final int position) {
                    holder.setText(R.id.item_title,model.title);
                    holder.setTextHTMLTwo(R.id.item_address,MessageFormat.format(STUDENT_COUNT,
                            String.valueOf(model.recCount),
                            String.valueOf(model.videoCount)));
                    holder.setText(R.id.item_state, MessageFormat.format(QXApplication.getContext().getResources().getString(R.string.course_person_count),
                            String.valueOf(model.regCount)));

                    holder.setVisible(R.id.item_paly,(CommonUtil.isRequestStr(model.videoUrl))?true:false);
                    holder.setImageState(R.id.item_img,model.fixImgUrl, OptionImageUtils.getRectRatio43());

                    holder.setOnClickListener(R.id.quit_regis, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            PopuDelete.showPopuWinDeleteCourse(back,
                                            new Delete(QXApplication.getContext().getResources().getString(R.string.quit_regis_course),
                                                    model.title),
                                            R.layout.popu_detele,
                                            position,
                                            new PopuDelete.DeleteState() {
                                                @Override
                                                public void state(boolean isSucess, int position) {
                                                        if(isSucess){
                                                            Map<String,String> map = new HashMap<String,String>();
                                                            map.put(AppHttpKey.TYPE,"2");
                                                            map.put(AppHttpKey.COURSE_ID,String.valueOf(model.id));
                                                            AppHttpRequest.appQuitState(ApplicationConfig.ATTEND_COURSE,
                                                                    map,
                                                                    new AppHttpRequest.OnAppHttpListener() {
                                                                        @Override
                                                                        public void onAppHttpState(boolean isState, String result) {
                                                                            if(isState){
                                                                                PromptManager.showToast(R.string.noregis_course_sucess);
                                                                                isForce = true;
                                                                                getInitNetwork(false);
                                                                            }
                                                                        }
                                                                    });
                                                        }
                                                }
                                            });
                        }
                    });
                }
            };

            adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    MyCourse obj = (MyCourse) adapter.getDatas().get(position);
                    int isClick = obj.isClick;
                    if(isClick == 1){
                        //不可以点击,当前项目 已经下线
                        ProjectDownHintUtil.proDownHint(appInfo,ProjectDownHintUtil.COURSE);
                        return;
                    }

                    TransformController.transformControllerModel(QXApplication.getContext(), CourseDetailActivity.class,obj);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });


            recycler.setAdapter(adapter);

        }

        if (isPull && isRequestList(models) && isRequestList(temps)) {
            //上拉加载数据
            models.addAll(temps);
        }

//        //刷新数据
        if (adapter != null)
            adapter.notifyDataSetChanged();



    }

    @Event(value = {R.id.back})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
        }
    }


    private void appInfo(){
        appInfo = SharePrefUtil.getString(SharePrefUtil.KEY.APP_INFO,"");

        if(!CommonUtil.isRequestStr(appInfo)){
            AppHttpRequest.httpAppInfo(new AppHttpRequest.OnAppHttpListener() {
                @Override
                public void onAppHttpState(boolean isState, String result) {
                    if(isState){
                        appInfo = result;
                    }
                }
            });
        }
    }

    @Override
    public void initSucessView() {}
    @Override
    public void initViewHandler() {
        if(recycler == null) return;
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.setLayoutManager(layoutVerManager);
    }
}
